<template>
    <el-dialog
        title="用户充值"
        :visible.sync="dialogVisible"
        width="500px"
        :close-on-click-modal="false"
        @closed="resetForm"
        append-to-body>
        <el-form :model="rechargeForm" :rules="rechargeRules" ref="rechargeFormRef" label-width="100px" size="small">
            <el-form-item label="用户ID">
                <el-input :value="currentUserId" disabled/>
            </el-form-item>
            <el-form-item label="用户名">
                <el-input :value="currentUsername" disabled/>
            </el-form-item>
            <el-form-item label="充值金额" prop="amount">
                <el-input-number v-model="rechargeForm.amount" :precision="2" :step="10" :min="0.01"
                                 placeholder="请输入"></el-input-number>
            </el-form-item>
            <el-form-item label="充值凭证" prop="proof">
                <el-upload
                    class="proof-uploader"
                    action="/admin/shop/imgUpload"
                    :headers="{ token: userInfo.token }"
                    :show-file-list="false"
                    :on-success="handleProofSuccess"
                    :before-upload="beforeProofUpload">
                    <img v-if="rechargeForm.proof" :src="getImageFullUrl(rechargeForm.proof)" class="proof-image">
                    <i v-else class="el-icon-plus proof-uploader-icon"></i>
                </el-upload>
                <div class="el-upload__tip">请上传jpg/png格式图片</div>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="rechargeForm.remark"/>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="closeDialog" size="small">取消</el-button>
            <el-button type="primary" @click="submitRecharge" size="small">确定充值</el-button>
        </div>
    </el-dialog>
</template>

<script>
import {mapState} from "vuex";

export default {
    data() {
        return {
            dialogVisible: false,
            currentUserId: null,
            currentUsername: '',
            rechargeForm: {
                amount: undefined,
                proof: '',
                remark:""
            },
            rechargeRules: {
                amount: [
                    {required: true, message: '请输入充值金额', trigger: 'blur'},
                    {type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur'}
                ],
                remark: [
                    {required: true, message: '请输入备注', trigger: 'blur'},
                ],
                proof: [
                    {required: true, message: '请上传充值凭证', trigger: 'change'}
                ]
            }
        };
    },
    computed: {
        ...mapState(["userInfo"]),
    },

    methods: {
        openDialog(userData) {
            this.currentUserId = userData.id;
            this.currentUsername = userData.username;
            this.dialogVisible = true;
        },
        closeDialog() {
            this.dialogVisible = false;
        },
        resetForm() {
            this.$refs.rechargeFormRef?.resetFields();
            this.rechargeForm.proof = '';
            this.currentUserId = null;
            this.currentUsername = '';
        },
        getImageFullUrl(relativePath) {
            if (!relativePath) return '';
            const baseUrl = process.env.NODE_ENV === 'production' ? $appConfig.baseUrl  : '';
            if (relativePath.startsWith('http://') || relativePath.startsWith('https://')) {
                return relativePath;
            }
            return `${baseUrl}/${relativePath}`.replace(/([^:]\/)\/+/g, "$1");
        },
        handleProofSuccess(res, file) {
            if (res.code === 200 && res.data) {
                this.rechargeForm.proof = Array.isArray(res.data) ? res.data[0] : res.data;
                this.$message.success('凭证上传成功');
                this.$refs.rechargeFormRef?.validateField('proof');
            } else {
                this.$message.error(res.msg || '凭证上传失败');
                this.rechargeForm.proof = '';
            }
        },
        beforeProofUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';

            if (!isJPG && !isPNG) {
                this.$message.error('上传凭证图片只能是 JPG/PNG 格式!');
            }
            return (isJPG || isPNG);
        },
        submitRecharge() {
            this.$refs.rechargeFormRef.validate((valid) => {
                if (valid) {
                    this.$confirm('您确定要为该用户充值吗？', '确认充值', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        const apiData = {
                            user_id: this.currentUserId,
                            amount: this.rechargeForm.amount,
                            remark: this.rechargeForm.remark,
                            proof: this.rechargeForm.proof
                        };

                        this.$http.post('/admin/User/recharge', apiData)
                            .then(result => {
                                if (result.code === 200) {
                                    this.$message.success('充值成功!');
                                    this.$emit('recharge-success');
                                    this.closeDialog();
                                } else {
                                    this.$message.error(result.msg || '充值失败');
                                }
                            })
                            .catch(error => {
                                console.error('Recharge API error:', error);
                                this.$message.error('充值请求失败，请稍后重试');
                            });

                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消充值'
                        });
                    });
                } else {
                    console.log('Recharge form validation failed');
                    return false;
                }
            });
        }
    }
};
</script>

<style scoped lang="less">
.proof-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.proof-uploader .el-upload:hover {
    border-color: #409EFF;
}

.proof-uploader-icon {
    font-size: 28px;
    color: #8c939d;
}

.proof-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
}

.dialog-footer {
    text-align: right;
}
/deep/.el-dialog__header{
    text-align: center !important;
}
</style>
